<template>
  <div class="products-page">
    <front-header></front-header>
    <div class="main-content">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <el-card shadow="hover" class="filter-card">
          <!-- 分类筛选 -->
          <div class="filter-group">
            <div class="filter-label">分类：</div>
            <div class="filter-options">
              <el-tag :effect="selectedCategory === '' ? 'dark' : 'plain'" @click="handleCategoryChange('')" class="filter-tag" type="success">全部</el-tag>
              <el-tag v-for="category in categories" :key="category.id" :effect="selectedCategory === category.id ? 'dark' : 'plain'"
                @click="handleCategoryChange(category.id)" class="filter-tag" type="success">{{ category.name }}</el-tag>
            </div>
          </div>

          <!-- 价格区间 -->
          <div class="filter-group">
            <div class="filter-label">价格：</div>
            <div class="filter-options">
              <el-tag :effect="priceRange === '' ? 'dark' : 'plain'" @click="handlePriceRangeChange('')" class="filter-tag" type="success">全部</el-tag>
              <el-tag v-for="(range, index) in priceRanges" :key="index" :effect="priceRange === range.value ? 'dark' : 'plain'"
                @click="handlePriceRangeChange(range.value)" class="filter-tag" type="success">{{ range.label }}</el-tag>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 排序和搜索区域 -->
      <div class="toolbar">
        <div class="sort-options">
          <el-radio-group v-model="sortBy" size="small">
            <el-radio-button 
              v-for="option in sortOptions" 
              :key="option.value" 
              :label="option.value"
            >{{ option.label }}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="search-box">
          <el-input 
            v-model="searchKeyword" 
            placeholder="搜索商品" 
            prefix-icon="el-icon-search" 
            clearable 
            @input="handleSearch"
          ></el-input>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="products-grid" v-loading="loading">
        <el-row :gutter="20" v-if="products.length > 0">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id" class="product-col">
            <product-card :product="product" />
          </el-col>
        </el-row>
        <div v-else class="empty-state">
          <i class="el-icon-goods"></i>
          <p>暂无商品</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination background :current-page.sync="currentPage" :page-size="pageSize" :total="total" layout="prev, pager, next, jumper"
          @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
    <front-footer></front-footer>
  </div>
</template>

<script>
import FrontHeader from '@/components/front/FrontHeader.vue'
import FrontFooter from '@/components/front/FrontFooter.vue'
import ProductCard from '@/components/front/ProductCard.vue'
import Request from '@/utils/request'
import { debounce } from 'lodash'

export default {
  name: 'Products',
  components: {
    FrontHeader,
    FrontFooter,
    ProductCard
  },
  data() {
    return {
      loading: false,
      products: [],
      categories: [],
      selectedCategory: '',
      priceRange: '',
      priceRanges: [
        { label: '0-50元', value: '0-50' },
        { label: '50-100元', value: '50-100' },
        { label: '100-200元', value: '100-200' },
        { label: '200元以上', value: '200-' }
      ],
      sortOptions: [
        { label: '默认排序', value: 'default' },
        { label: '销量优先', value: 'sales,desc' },
        { label: '价格从低到高', value: 'price,asc' },
        { label: '价格从高到低', value: 'price,desc' }
      ],
      sortBy: 'default',
      searchKeyword: '',
      currentPage: 1,
      pageSize: 12,
      total: 0,
      debouncedSearch: null
    }
  },
  methods: {
    // 获取商品分类
    async getCategories() {
      try {
        const res = await Request.get('/category/all')
        if (res.code === '0') {
          this.categories = res.data
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },
    // 获取商品列表
    async getProducts() {
      this.loading = true
      try {
        const params = {
          status: 1,
          currentPage: this.currentPage,
          size: this.pageSize
        }

        // 添加分类筛选
        if (this.selectedCategory) {
          params.categoryId = this.selectedCategory
        }

        // 添加价格区间筛选
        if (this.priceRange) {
          const [min, max] = this.priceRange.split('-')
          if (min) params.minPrice = min
          if (max) params.maxPrice = max
        }

        // 添加排序
        if (this.sortBy !== 'default') {
          const [field, order] = this.sortBy.split(',')
          params.sortField = field
          params.sortOrder = order
        }

        // 添加搜索关键词
        if (this.searchKeyword) {
          params.name = this.searchKeyword
        }

        const res = await Request.get('/product/page', { params })
        if (res.code === '0') {
          if (res.data && res.data.records) {
            this.products = res.data.records.map(product => ({
              ...product,
              isFavorite: false,
              imageUrl: product.imageUrl?.startsWith('http') ? product.imageUrl : `${product.imageUrl}`
            }))
            this.total = res.data.total
          } else {
            this.products = []
            this.total = 0
          }
        } else {
          this.products = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        this.$message.error('获取商品列表失败')
        this.products = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    handleCategoryChange(categoryId) {
      this.selectedCategory = categoryId
      this.currentPage = 1
      this.getProducts()
    },
    handlePriceRangeChange(range) {
      this.priceRange = range
      this.currentPage = 1
      this.getProducts()
    },
    handleSearch() {
      this.debouncedSearch()
    },
    handlePageChange(page) {
      this.getProducts()
    },
    // 监听路由变化
    handleRouteChange() {
      const query = {}
      if (this.selectedCategory) {
        query.category = this.selectedCategory
      }
      if (this.searchKeyword) {
        query.keyword = this.searchKeyword
      }
      // 更新URL，但不触发路由变化
      this.$router.replace({ query }).catch(() => {})
    }
  },
  watch: {
    // 监听搜索关键词变化
    searchKeyword() {
      this.handleSearch()
      this.handleRouteChange()
    },
    
    // 监听分类变化
    selectedCategory() {
      this.handleRouteChange()
    },
    sortBy() {
      this.currentPage = 1
      this.getProducts()
    }
  },
  created() {
    // 创建防抖的搜索函数
    this.debouncedSearch = debounce(() => {
      this.currentPage = 1
      this.getProducts()
    }, 300)

    this.getCategories()
    this.getProducts()
    
    // 从URL获取查询参数
    const { category, keyword } = this.$route.query
    if (category) this.selectedCategory = category
    if (keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    }
  },
  beforeDestroy() {
    // 清除防抖函数
    if (this.debouncedSearch) {
      this.debouncedSearch.cancel()
    }
  }
}
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f9f9f9;
  color: #333;
}

.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
  width: 100%;
  box-sizing: border-box;
  max-height: 100%;
  overflow: auto;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 30px;
}

.filter-card {
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05) !important;
}

.filter-group {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-label {
  width: 60px;
  font-size: 15px;
  font-weight: 500;
  color: #333;
  line-height: 32px;
  flex-shrink: 0;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-tag {
  cursor: pointer;
  margin-right: 0;
  transition: all 0.3s ease;
}

.filter-tag:hover {
  transform: translateY(-2px);
}

/* 排序和搜索区域 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 15px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.03);
}

.search-box {
  width: 250px;
}

/* 商品列表 */
.products-grid {
  margin-bottom: 40px;
  min-height: 400px;
}

.product-col {
  margin-bottom: 25px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05);
}

.empty-state i {
  font-size: 60px;
  color: #ddd;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #999;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin: 30px 0 50px;
}

/* 响应式布局 */
@media (max-width: 992px) {
  .main-content {
    margin: 30px auto;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-label {
    width: 50px;
    font-size: 14px;
  }
}

@media (max-width: 576px) {
  .main-content {
    padding: 0 15px;
    margin: 20px auto;
  }
  
  .filter-group {
    flex-direction: column;
  }
  
  .filter-label {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style> 